<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <el-alert
        effect="dark"
        :closable="false"
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
      ></el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col style="display:flex" :span="8">
          <span class="shoppage">选择商品分类：</span>
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader
            v-model="selectedCateKeys"
            :options="catelist"
            :props="cateProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tabs 切换区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数的按钮 -->
          <el-button
            size="mini"
            type="primary"
            :disabled="isBtnDisabled"
            @click="addDialogVisible=true"
          >添加参数</el-button>
          <!-- 添加参数表格区域 -->
          <el-table :data="manyTableData" stripe style="width: 100%" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  @close="handleClose(i,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInputRef"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="delParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加属性的按钮 -->
          <el-button
            size="mini"
            type="primary"
            :disabled="isBtnDisabled"
            @click="addDialogVisible=true"
          >添加属性</el-button>
          <!-- 添加属性表格区域 -->
          <el-table :data="onlyTableData" stripe style="width: 100%" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  @close="handleClose(i,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInputRef"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="delParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加的模态框 -->
      <el-dialog
        :title="'添加'+addlogtitle"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addHandleClose"
      >
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
          <el-form-item :label="addlogtitle" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑的模态框 -->
      <el-dialog
        :title="'编辑'+addlogtitle"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editHandleClose"
      >
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
          <el-form-item :label="addlogtitle" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParams">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 编辑的数据
      editForm: {
        attr_name: ''
      },
      // 编辑模态框的显示与隐藏
      editDialogVisible: false,
      // 添加的验证规则
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 编辑的验证规则
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 添加的数据
      addForm: {
        attr_name: ''
      },
      // 添加模态框的显示与隐藏
      addDialogVisible: false,
      // 动态属性的数据
      onlyTableData: [],
      // 动态参数的数据
      manyTableData: [],
      // 被激活的页签的名称
      activeName: 'many',
      // 联级选择器 选中数据的id
      selectedCateKeys: '',
      // 获取联级选择器的数据
      catelist: [],
      // 联级选择器的配置
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        expandTrigger: 'hover'
      }
    }
  },
  created() {
    this.getCateList()
  },
  computed: {
    // 判断用户是否激活了联级选择器
    isBtnDisabled() {
      if (this.selectedCateKeys.length !== 3) {
        return true
      }
      return false
    },
    // 当前选中的三级分类的Id
    cataid() {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[this.selectedCateKeys.length - 1]
      }
      return null
    },
    addlogtitle() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  },
  methods: {
    // newTag的删除事件
    handleClose(i, row) {
      row.attr_vals = row.attr_vals.splice(i, 1)
      this.savegetdel(row)
    },
    // 展示添加new  tag 的input的输入框
    showInput(row) {
      row.inputVisible = true

      this.$nextTick(() => {
        this.$refs.saveTagInputRef.$refs.input.focus()
      })
    },
    // 按下回车或者失去焦点就会触发
    handleInputConfirm(row) {
      if (row.inputValue.trim() === '') {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 把内容添加到attr_vals中
      row.attr_vals.push(row.inputValue)
      // 并且清空表单内容
      row.inputValue = ''
      row.inputVisible = false

      // 调用接口
      this.savegetdel(row)
      // console.log(row)
      // console.log(result)
    },
    // 由于添加和删除都可以调用这个接口所以单独封装出来
    async savegetdel(row) {
      let { data: res } = await this.$axios.put(
        `categories/${this.cataid}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) {
        return this.$Message.error('失败,请重试')
      }
      this.$Message.success('恭喜操作成功')
    },
    // 点击删除按钮
    async delParams(attrid) {
      let result = await this.$confirm(
        '此操作将永久删除该数据 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      console.log(result)

      if (result !== 'confirm') {
        return this.$Message.info('已取消删除！')
      }
      let { data: res } = await this.$axios.delete(
        `categories/${this.cataid}/attributes/${attrid}`
      )

      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$Message.error('删除失败请重试')
      }
      this.$Message.success('恭喜删除成功')
      this.getParamsData()
    },
    // 点击编辑按钮的时候请求数据 并且展示模态框
    async showEditDialog(attrId) {
      let { data: res } = await this.$axios.get(
        `categories/${this.cataid}/attributes/${attrId}`,
        {
          params: { attr_sel: this.activeName }
        }
      )
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$Message.error('获取失败')
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 点击确认发起编辑请求
    async editParams() {
      let { data: res } = await this.$axios.put(
        `categories/${this.cataid}/attributes/${this.editForm.attr_id}`,
        {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        }
      )
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$Message.error('编辑失败')
      }
      this.$Message.success('恭喜编辑成功')
      this.getParamsData()
      this.editDialogVisible = false
    },
    // 编辑模态框关闭时触发
    editHandleClose() {
      this.$refs.editFormRef.resetFields()
    },
    // 点击确认发起添加请求
    addParams() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$Message.error('请输入参数名称')
        }
        let { data: res } = await this.$axios.post(
          `categories/${this.cataid}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$Message.error('添加失败')
        }
        this.$Message.success('恭喜' + res.meta.msg)

        this.getParamsData()
        this.addDialogVisible = false
      })
    },
    // 添加模态框关闭时触发
    addHandleClose() {
      this.$refs.addFormRef.resetFields()
    },

    // 获取参数的列表数据 分装为函数
    async getParamsData() {
      // 要求必须选择3级分类进行筛选
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        this.onlyTableData = []
        this.manyTableData = []
        return
      }
      // console.log(this.selectedCateKeys)
      // 发起请求
      let { data: res } = await this.$axios.get(
        `categories/${this.cataid}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )

      console.log(res)
      if (res.meta.status !== 200) {
        return this.$Message.error('获取数据失败')
      }
      res.data.forEach(item => {
        // 把字符串转化为数组
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 在数据中添加两个属性
        // 一个用来控制显示与隐藏
        item.inputVisible = false
        //  一个用来接收文本框内容
        item.inputValue = ''
        console.log(item)
      })
      // console.log(res.data)

      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 点击tab选择框的事件
    handleTabClick() {
      // console.log(this.activeName)
      this.getParamsData()
    },
    // 联级选择器改变事件触发
    handleChange() {
      this.getParamsData()
    },
    // 获取级联选择器的数据
    async getCateList() {
      let { data: res } = await this.$axios.get('categories')
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$Message.error('error' + res.meta.msg)
      }
      this.catelist = res.data
      // console.log(this.catelist)
    }
  }
}
</script>
<style lang="less" scoped>
.cat_opt {
  margin-top: 15px;
}
.shoppage {
  width: 180px;
  line-height: 38px;
}
.el-tag {
  margin: 7px;
}
.input-new-tag {
  width: 120px;
}
</style>
